<template>
  <view class="container">
    <view v-if="loading" class="loading-state">
      <uni-load-more status="loading" />
    </view>

    <view v-else-if="product" class="product-detail">
      <!-- 商品图片 -->
      <view class="product-image">
        <image :src="product.image_url || '/static/icons/default-product.svg'" mode="aspectFill" class="image"
          @error="handleImageError" />
        <view class="tags">
          <view v-if="product.is_hot" class="tag hot-tag">热门</view>
          <view v-if="product.is_new" class="tag new-tag">新品</view>
        </view>
      </view>

      <!-- 商品信息 -->
      <view class="product-info">
        <view class="product-name">{{ product.name || '未知商品' }}</view>

        <view class="product-price">
          <view class="points-price">
            <text class="price-number">{{ product.points_price || 0 }}</text>
            <text class="price-unit">积分</text>
          </view>
          <view v-if="product.original_price && product.original_price > 0" class="original-price">
            原价: {{ product.original_price }}元
          </view>
        </view>

        <view class="product-stock">
          <text v-if="product.stock_quantity > 0" class="in-stock">
            库存: {{ product.stock_quantity }}
          </text>
          <text v-else class="out-of-stock">缺货</text>
        </view>

        <view class="product-category">
          <text class="label">分类:</text>
          <text class="value">{{ product.categoryName || getCategoryName(product.category) || '其他' }}</text>
        </view>

        <view v-if="product.type" class="product-type">
          <text class="label">类型:</text>
          <text class="value">{{ getTypeName(product.type) || product.type }}</text>
        </view>
      </view>

      <!-- 商品描述 -->
      <view class="product-description">
        <view class="section-title">商品描述</view>
        <view class="description-content">
          {{ product.description || '暂无描述' }}
        </view>
      </view>

      <!-- 纸张规格 - 针对打印和复印类商品 -->
      <view v-if="isPrintOrCopyProduct && hasSpecifications" class="product-specifications">
        <view class="section-title">专业纸张规格</view>
        <view class="spec-list">
          <view class="spec-item" v-if="getSpecValue('paper_type')">
            <text class="spec-label">纸张类型:</text>
            <view class="spec-value">
              {{ getPaperTypeName(getSpecValue('paper_type')).split(' - ')[0] }}
              <text class="spec-detail" v-if="getPaperTypeName(getSpecValue('paper_type')).includes(' - ')">
                {{ getPaperTypeName(getSpecValue('paper_type')).split(' - ')[1] }}
              </text>
            </view>
          </view>
          <view class="spec-item" v-if="getSpecValue('paper_weight')">
            <text class="spec-label">纸张克重:</text>
            <view class="spec-value">
              {{ getPaperWeightName(getSpecValue('paper_weight')).split(' - ')[0] }}
              <text class="spec-detail" v-if="getPaperWeightName(getSpecValue('paper_weight')).includes(' - ')">
                {{ getPaperWeightName(getSpecValue('paper_weight')).split(' - ')[1] }}
              </text>
            </view>
          </view>
          <view class="spec-item" v-if="getSpecValue('paper_size')">
            <text class="spec-label">纸张尺寸:</text>
            <view class="spec-value">
              {{ getPaperSizeName(getSpecValue('paper_size')).split(' - ')[0] }}
              <text class="spec-detail" v-if="getPaperSizeName(getSpecValue('paper_size')).includes(' - ')">
                {{ getPaperSizeName(getSpecValue('paper_size')).split(' - ')[1] }}
              </text>
            </view>
          </view>
          <view class="spec-item" v-if="getSpecValue('color_mode')">
            <text class="spec-label">打印模式:</text>
            <text class="spec-value">{{ getSpecValue('color_mode') === 'color' ? '彩色' : '黑白' }}</text>
          </view>
          <view class="spec-item" v-if="getSpecValue('sides')">
            <text class="spec-label">打印面数:</text>
            <text class="spec-value">{{ getSpecValue('sides') === 'double' ? '双面' : '单面' }}</text>
          </view>
          <view class="spec-item" v-if="getSpecValue('dpi')">
            <text class="spec-label">打印精度:</text>
            <text class="spec-value">{{ getSpecValue('dpi') }}DPI</text>
          </view>
          <view class="spec-item" v-if="getSpecValue('finish')">
            <text class="spec-label">表面处理:</text>
            <view class="spec-value">
              {{ getFinishName(getSpecValue('finish')).split(' - ')[0] }}
              <text class="spec-detail" v-if="getFinishName(getSpecValue('finish')).includes(' - ')">
                {{ getFinishName(getSpecValue('finish')).split(' - ')[1] }}
              </text>
            </view>
          </view>
        </view>
      </view>

      <!-- 装订规格 - 针对装订类商品 -->
      <view v-else-if="isBindingProduct" class="product-specifications">
        <view class="section-title">专业装订规格</view>
        <view class="spec-list">
          <view class="spec-item" v-if="getSpecValue('binding_type')">
            <text class="spec-label">装订类型:</text>
            <view class="spec-value">
              {{ getBindingTypeName(getSpecValue('binding_type')).split(' - ')[0] }}
              <text class="spec-detail" v-if="getBindingTypeName(getSpecValue('binding_type')).includes(' - ')">
                {{ getBindingTypeName(getSpecValue('binding_type')).split(' - ')[1] }}
              </text>
            </view>
          </view>
          <view class="spec-item" v-if="getSpecValue('max_pages')">
            <text class="spec-label">最大页数:</text>
            <text class="spec-value">{{ getSpecValue('max_pages') }}页</text>
          </view>
          <view class="spec-item" v-if="getSpecValue('cover_options')">
            <text class="spec-label">封面选项:</text>
            <text class="spec-value">{{ getSpecValue('cover_options') }}</text>
          </view>
          <view v-for="(value, key) in getOtherBindingSpecs" :key="key" class="spec-item">
            <text class="spec-label">{{ formatSpecKey(key) }}:</text>
            <text class="spec-value">{{ value }}</text>
          </view>
        </view>
      </view>

      <!-- 其他商品规格 -->
      <view v-else-if="hasOtherSpecifications" class="product-specifications">
        <view class="section-title">商品规格</view>
        <view class="spec-list">
          <view v-if="product.specifications" v-for="(value, key) in product.specifications" :key="key"
            class="spec-item">
            <text class="spec-label">{{ formatSpecKey(key) }}:</text>
            <text class="spec-value">{{ value }}</text>
          </view>
          <!-- 显示基本规格信息 -->
          <view v-if="!product.specifications">
            <view v-if="product.paper_type" class="spec-item">
              <text class="spec-label">纸张类型:</text>
              <text class="spec-value">{{ product.paper_type }}</text>
            </view>
            <view v-if="product.paper_size" class="spec-item">
              <text class="spec-label">纸张尺寸:</text>
              <text class="spec-value">{{ product.paper_size }}</text>
            </view>
            <view v-if="product.color_type" class="spec-item">
              <text class="spec-label">颜色类型:</text>
              <text class="spec-value">{{ product.color_type === 'color' ? '彩色' : product.color_type === 'bw' ? '黑白' :
                '双色' }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 底部操作栏 -->
      <view class="bottom-actions">
        <view class="user-points">
          <text class="points-label">我的积分:</text>
          <text class="points-value">{{ userPointsCount }}</text>
        </view>

        <view class="action-buttons">
          <button class="btn btn-primary" :disabled="!canExchange" @click="handleExchange">
            {{ exchangeButtonText }}
          </button>
        </view>
      </view>
    </view>

    <!-- 错误状态 -->
    <view v-else class="error-state">
      <image src="/static/icons/error.png" class="error-icon" />
      <text class="error-text">商品不存在或已下架</text>
      <button class="btn btn-secondary" @click="goBack">返回</button>
    </view>
  </view>
</template>

<script>
import productsApi from '@/api/products'
import { mapState, mapGetters } from 'vuex'
import productValidator, { processApiResponse, formatForDisplay } from '@/utils/productDataValidator'
import { handleError } from '@/utils/errorHandler'
import { showLoading, hideLoading, isLoading } from '@/utils/loadingManager'
import { isUnauthorizedError, authCheckMixin } from '@/utils/authErrorHandler'

export default {
  name: 'ProductDetailPage',
  mixins: [authCheckMixin],
  data() {
    return {
      product: null,
      loading: true,
      productId: null,
      userPointsCount: 0,

      retryCount: 0,
      maxRetries: 3,
      error: null,
      categoryNames: {
        'print': '打印服务',
        'copy': '复印服务',
        'service': '服务类',
        'goods': '商品类',
        'binding': '装订服务',
        'other': '其他'
      },
      typeNames: {
        // 后端实际返回的类型
        'color_print': '彩色打印',
        'bw_print': '黑白打印',
        'copy': '复印服务',
        'binding': '装订服务',
        'laminating': '塑封服务',
        'layout': '排版服务',
        'office_supplies': '办公用品',

        // 兼容旧的类型名
        'color': '彩色打印',
        'black_white': '黑白打印',
        'spiral_binding': '螺旋装订',
        'perfect_binding': '胶装',
        'saddle_binding': '骑马钉',
        'scan': '扫描服务'
      },
      paperTypes: {
        'normal': '普通纸 - 日常文档打印',
        'coated': '铜版纸 - 高质量彩印',
        'photo': '相纸 - 照片打印',
        'cardstock': '卡纸 - 名片海报',
        'recycled': '再生纸 - 环保选择'
      },
      defaultImageUrl: '/static/icons/default-product.svg',
      paperWeights: {
        '70': '70g - 轻薄经济',
        '80': '80g - 标准文档',
        '100': '100g - 优质文档',
        '120': '120g - 高档印刷',
        '150': '150g - 厚实质感',
        '200': '200g - 卡片级别',
        '250': '250g - 封面专用'
      },
      paperSizes: {
        'A4': 'A4 - 210×297mm',
        'A3': 'A3 - 297×420mm',
        'A5': 'A5 - 148×210mm',
        'B4': 'B4 - 250×353mm',
        'B5': 'B5 - 176×250mm',
        'Letter': 'Letter - 216×279mm',
        'Legal': 'Legal - 216×356mm'
      },
      finishTypes: {
        'matte': '哑光 - 无反光',
        'glossy': '光面 - 亮丽色彩',
        'satin': '缎面 - 柔和质感',
        'luster': '绒面 - 专业级'
      },
      bindingTypes: {
        'spiral': '螺旋装订 - 可180度翻开',
        'perfect': '胶装 - 书本式装订',
        'saddle': '骑马钉 - 简单牢固',
        'wire': '铁丝装订 - 经济实用',
        'comb': '梳式装订 - 易于翻页'
      }
    }
  },

  computed: {
    ...mapState('auth', ['userInfo', 'isAuthenticated']),
    ...mapGetters('auth', ['isLoggedIn']),

    canExchange() {
      if (!this.product) return false
      return this.product.stock_quantity > 0 && this.userPointsCount >= this.product.points_price
    },

    exchangeButtonText() {
      if (!this.product) return '加载中...'
      if (this.product.stock_quantity <= 0) return '缺货'
      if (this.userPointsCount < this.product.points_price) return '积分不足'
      return '立即兑换'
    },

    // 判断是否为打印或复印类商品
    isPrintOrCopyProduct() {
      if (!this.product || !this.product.type) return false
      return this.product.type.includes('print') || this.product.type.includes('copy')
    },

    // 判断是否为装订类商品
    isBindingProduct() {
      if (!this.product || !this.product.type) return false
      return this.product.type.includes('binding')
    },

    // 判断是否有规格信息
    hasSpecifications() {
      if (!this.product) return false

      // 如果有specifications对象
      if (this.product.specifications &&
        typeof this.product.specifications === 'object' &&
        Object.keys(this.product.specifications).length > 0) {
        return true
      }

      // 或者有任何规格相关的字段
      return !!(this.product.paper_type ||
        this.product.paper_size ||
        this.product.color_type)
    },

    // 获取装订类商品的其他规格（排除已单独显示的规格）
    getOtherBindingSpecs() {
      if (!this.product) return {}

      if (this.product.specifications) {
        const { binding_type, max_pages, cover_options, ...otherSpecs } = this.product.specifications
        return otherSpecs
      }

      // 如果没有specifications对象，返回空对象
      return {}
    },

    // 判断是否有其他规格信息需要显示
    hasOtherSpecifications() {
      if (!this.product) return false

      // 如果是打印或复印类商品，不在这里显示规格
      if (this.isPrintOrCopyProduct) return false

      // 如果是装订类商品，不在这里显示规格
      if (this.isBindingProduct) return false

      // 有specifications对象或者有基本规格字段
      return !!(this.product.specifications ||
        this.product.paper_type ||
        this.product.paper_size ||
        this.product.color_type)
    }
  },

  async onLoad(options) {
    try {
      // 确保store正确初始化
      await this.$store.dispatch('auth/initAuth')

      if (options.id) {
        this.productId = parseInt(options.id)
        await this.initPageData()
      } else {
        this.loading = false
        uni.showToast({
          title: '商品ID不存在',
          icon: 'none'
        })
        setTimeout(() => {
          this.goBack()
        }, 1500)
      }
    } catch (error) {
      console.error('页面初始化失败:', error)
      this.loading = false
      uni.showToast({
        title: '页面加载失败',
        icon: 'none'
      })
    }
  },

  onPullDownRefresh() {
    this.refreshData().then(() => {
      uni.stopPullDownRefresh()
    })
  },

  onShareAppMessage() {
    if (this.product) {
      return {
        title: `【${this.product.name}】${this.product.points_price}积分兑换`,
        path: `/pages/products/detail?id=${this.productId}`,
        imageUrl: this.product.image_url || this.defaultImageUrl
      }
    }
    return {
      title: '云打印商品兑换',
      path: '/pages/index/index'
    }
  },

  methods: {
    // 初始化页面数据
    async initPageData() {
      const loadingKey = 'init_product_detail'

      try {
        this.loading = true
        showLoading(loadingKey, { title: '加载商品详情...' })

        await Promise.all([
          this.loadProductDetail(),
          this.loadUserPoints()
        ])
      } catch (error) {
        console.error('初始化页面数据失败:', error)

        handleError(error, {
          action: 'init_product_detail',
          productId: this.productId
        }, {
          showModal: true,
          title: '加载失败',
          onRetry: () => this.initPageData()
        })

        // 处理初始化失败
        this.error = '商品信息加载失败'
      } finally {
        this.loading = false
        hideLoading(loadingKey)
      }
    },



    // 刷新数据
    async refreshData() {
      try {
        // 重新从API获取数据

        const results = await Promise.all([
          this.loadProductDetail(),
          this.loadUserPoints()
        ])

        // 如果两个API都成功获取数据
        if (results[0] && results[1]) {
          uni.showToast({
            title: '刷新成功',
            icon: 'success',
            duration: 1500
          })
        } else {
          uni.showToast({
            title: '部分数据刷新成功',
            icon: 'none',
            duration: 1500
          })
        }
      } catch (error) {
        console.error('刷新数据失败:', error)
        uni.showToast({
          title: '刷新失败',
          icon: 'none'
        })

        // 处理刷新失败
        if (!this.product) {
          this.error = '刷新失败，请重试'
        }
      }
    },

    // 加载商品详情
    async loadProductDetail() {
      try {
        console.log('正在加载商品详情，ID:', this.productId)

        // 尝试使用API获取商品详情
        try {
          const response = await productsApi.getProductDetail(this.productId)

          // 使用数据验证器处理API响应
          const processedResponse = processApiResponse(response)

          if (processedResponse.success) {
            // 格式化商品数据
            this.product = formatForDisplay(processedResponse.data)
            this.error = null
            this.retryCount = 0

            console.log('商品详情加载成功:', this.product)

            // 预加载商品图片
            if (this.product.image_url) {
              uni.getImageInfo({
                src: this.product.image_url,
                fail: () => {
                  console.warn('商品图片加载失败，使用默认图片')
                  this.product.image_url = this.defaultImageUrl
                }
              })
            }
            return true
          } else {
            throw new Error(processedResponse.message || 'API返回错误')
          }
        } catch (apiError) {
          console.error('API获取商品详情失败:', apiError)
          this.retryCount++

          // 处理API失败
          if (!this.product) {
            this.error = '商品不存在或已下架'
            this.handleApiError(this.error)
          }

          return !!this.product
        }
      } catch (error) {
        console.error('加载商品详情异常:', error)
        this.error = '加载商品详情失败'
        this.handleApiError(this.error, error)
        return false
      }
    },

    // 加载用户积分
    async loadUserPoints() {
      try {
        // 确保store已初始化
        if (!this.$store.state.auth) {
          await this.$store.dispatch('auth/initAuth')
        }

        // 首先尝试从store获取
        const authState = this.$store.state.auth
        if (authState && authState.userInfo && typeof authState.userInfo.points !== 'undefined') {
          this.userPointsCount = authState.userInfo.points
          return true
        }

        // 如果用户未登录，使用默认积分
        if (!this.isLoggedIn) {
          this.userPointsCount = 0
          return true
        }

        // 如果store中没有，则尝试从API获取
        try {
          // 使用统一的API调用方式
          const { getPointsBalance } = require('@/api/points')
          const result = await getPointsBalance()

          if (result && result.success) {
            this.userPointsCount = result.data.availablePoints || 0
            return true
          } else {
            throw new Error('API返回错误')
          }
        } catch (apiError) {
          console.warn('API获取积分失败，使用模拟数据:', apiError)

          // 使用默认积分
          this.userPointsCount = 500

          return false
        }
      } catch (error) {
        console.error('加载用户积分失败:', error)
        this.userPointsCount = 0
        return false
      }
    },

    // 处理API错误
    handleApiError(message, error = null) {
      if (error) {
        console.error(`${message}:`, error)
      }

      this.error = message

      // 显示错误提示
      const friendlyMessage = this.getErrorMessage(error || { message })
      uni.showToast({
        title: friendlyMessage,
        icon: 'none',
        duration: 3000
      })
    },

    // 获取友好的错误信息
    getErrorMessage(error) {
      if (!error) return '未知错误'

      const message = error.message || error.toString()

      if (message.includes('timeout')) {
        return '请求超时，请检查网络连接'
      } else if (message.includes('network') || message.includes('fail')) {
        return '网络连接失败，请检查网络设置'
      } else if (message.includes('404') || message.includes('不存在')) {
        return '商品不存在或已下架'
      } else if (message.includes('500')) {
        return '服务器内部错误'
      } else {
        return '加载失败，请稍后重试'
      }
    },



    // 获取分类名称
    getCategoryName(category) {
      return this.categoryNames[category] || category
    },

    // 获取类型名称
    getTypeName(type) {
      return this.typeNames[type] || type
    },

    // 获取纸张类型名称
    getPaperTypeName(paperType) {
      if (!paperType) return ''

      // 如果是后端返回的完整描述，直接返回
      if (typeof paperType === 'string' && (
        paperType.includes('纸') ||
        paperType.includes('g') ||
        paperType.length > 10
      )) {
        return paperType
      }

      // 否则从映射表中查找
      return this.paperTypes[paperType] || paperType
    },

    // 获取纸张克重名称
    getPaperWeightName(paperWeight) {
      if (!paperWeight) return ''

      // 如果已经是完整描述，直接返回
      if (typeof paperWeight === 'string' && paperWeight.includes('g')) {
        return paperWeight
      }

      // 否则从映射表中查找，或者添加g后缀
      return this.paperWeights[paperWeight] || `${paperWeight}g`
    },

    // 获取表面处理名称
    getFinishName(finish) {
      return this.finishTypes[finish] || finish
    },

    // 获取装订类型名称
    getBindingTypeName(bindingType) {
      return this.bindingTypes[bindingType] || bindingType
    },

    // 获取纸张尺寸名称
    getPaperSizeName(paperSize) {
      return this.paperSizes[paperSize] || paperSize
    },

    // 格式化规格键名
    formatSpecKey(key) {
      // 将下划线转换为空格，并将首字母大写
      return key.split('_')
        .map(word => word.charAt(0).toUpperCase() + word.slice(1))
        .join(' ')
    },

    // 安全获取规格值
    getSpecValue(key) {
      if (!this.product) return null

      // 如果有specifications对象，优先使用
      if (this.product.specifications && this.product.specifications[key]) {
        return this.product.specifications[key]
      }

      // 否则从产品的直接属性中获取
      const fieldMapping = {
        'paper_type': this.product.paper_type,
        'paper_size': this.product.paper_size,
        'color_mode': this.product.color_type,
        'paper_weight': this.extractPaperWeight(this.product.paper_type), // 从paper_type中提取克重信息
        'sides': 'single', // 默认单面
        'dpi': '600', // 默认DPI
        'finish': 'matte' // 默认哑光
      }

      return fieldMapping[key] || null
    },

    // 从纸张类型中提取克重信息
    extractPaperWeight(paperType) {
      if (!paperType) return null

      // 使用正则表达式提取数字+g的格式
      const match = paperType.match(/(\d+)g/i)
      return match ? match[1] : null
    },

    // API重试机制
    async retryApiCall(apiCall, maxRetries = 3, delay = 1000) {
      for (let i = 0; i < maxRetries; i++) {
        try {
          return await apiCall()
        } catch (error) {
          console.log(`API调用失败，第${i + 1}次重试:`, error.message)

          if (i === maxRetries - 1) {
            throw error // 最后一次重试失败，抛出错误
          }

          // 如果是超时错误，等待后重试
          if (error.message.includes('超时') || error.message.includes('timeout')) {
            await new Promise(resolve => setTimeout(resolve, delay * (i + 1)))
          } else {
            throw error // 非超时错误，直接抛出
          }
        }
      }
    },

    // 处理兑换
    handleExchange() {
      // 检查登录状态
      if (!this.checkAuth()) {
        uni.showModal({
          title: '需要登录',
          content: '兑换商品需要先登录，是否前往登录？',
          confirmText: '去登录',
          cancelText: '取消',
          success: (res) => {
            if (res.confirm) {
              const currentPage = `/pages/products/detail?id=${this.productId}`
              this.goToLogin(currentPage)
            }
          }
        })
        return
      }

      // 验证商品数据
      if (!this.product || !this.product.id) {
        uni.showToast({
          title: '商品信息错误',
          icon: 'none'
        })
        return
      }

      if (!this.canExchange) {
        if (this.product.stock_quantity <= 0) {
          uni.showModal({
            title: '商品缺货',
            content: '该商品暂时缺货，您可以选择其他商品或稍后再试',
            confirmText: '查看其他商品',
            cancelText: '稍后再试',
            success: (res) => {
              if (res.confirm) {
                uni.navigateBack()
              }
            }
          })
        } else if (this.userPointsCount < this.product.points_price) {
          const shortage = this.product.points_price - this.userPointsCount
          uni.showModal({
            title: '积分不足',
            content: `当前积分${this.userPointsCount}，还差${shortage}积分。您可以通过完成任务获得更多积分。`,
            confirmText: '去赚积分',
            cancelText: '取消',
            success: (res) => {
              if (res.confirm) {
                uni.navigateTo({
                  url: '/pages/points/earn'
                })
              }
            }
          })
        } else {
          uni.showToast({
            title: '暂时无法兑换',
            icon: 'none'
          })
        }
        return
      }

      // 显示兑换确认对话框
      uni.showModal({
        title: '确认兑换',
        content: `确定使用${this.product.points_price}积分兑换"${this.product.name}"吗？兑换后积分将立即扣除。`,
        confirmText: '确认兑换',
        cancelText: '再想想',
        success: (res) => {
          if (res.confirm) {
            this.processExchange()
          }
        }
      })
    },

    // 处理兑换流程
    async processExchange() {
      // 防止重复提交
      if (this.loading) {
        console.log('正在处理中，防止重复提交')
        return
      }

      this.loading = true

      uni.showLoading({
        title: '处理中...',
        mask: true
      })

      try {
        console.log('开始处理兑换，商品ID:', this.productId)



        // 实际API调用
        try {
          console.log('调用API创建订单')

          // 动态导入订单API
          const ordersApi = await import('@/api/orders')
          const createOrder = ordersApi.createOrder || ordersApi.default?.createOrder

          if (!createOrder) {
            throw new Error('订单API不可用')
          }

          const orderData = {
            items: [{
              productId: this.productId,
              quantity: 1
            }],
            type: 'exchange',
            pointsUsed: this.product.points_price,
            paymentMethod: 'points'
          }

          // 添加重试机制
          const result = await this.retryApiCall(() => createOrder(orderData), 3)

          uni.hideLoading()

          if (result && result.success) {
            console.log('订单创建成功:', result.data)

            // 检查是否有警告信息
            if (result.warnings && result.warnings.length > 0) {
              console.warn('订单创建警告:', result.warnings)
            }

            uni.showToast({
              title: '兑换成功！',
              icon: 'success',
              duration: 2000
            })

            // 更新用户积分和商品库存
            this.userPointsCount = Math.max(0, this.userPointsCount - this.product.points_price)
            this.product.stock_quantity = Math.max(0, this.product.stock_quantity - 1)

            // 更新store中的用户积分（如果存在）
            try {
              if (this.$store.state.auth.userInfo) {
                this.$store.commit('auth/SET_USER_INFO', {
                  ...this.$store.state.auth.userInfo,
                  points: this.userPointsCount
                })
              }
            } catch (error) {
              console.warn('更新store用户积分失败:', error)
            }

            // 延迟跳转到订单详情页
            setTimeout(() => {
              uni.showModal({
                title: '兑换成功',
                content: '您的兑换订单已生成，可在"我的订单"中查看详情',
                confirmText: '查看订单',
                cancelText: '继续浏览',
                success: (res) => {
                  if (res.confirm) {
                    const orderId = result.data?.id || result.data?.orderId
                    if (orderId) {
                      uni.navigateTo({
                        url: `/pages/orders/detail?id=${orderId}`
                      })
                    } else {
                      uni.navigateTo({
                        url: '/pages/orders/list?status=pending'
                      })
                    }
                  }
                }
              })
            }, 1500)
          } else {
            throw new Error(result?.message || 'API返回错误')
          }
        } catch (apiError) {
          console.error('API兑换失败:', apiError)
          uni.hideLoading()

          // 检查是否为未授权错误，如果是则不显示错误提示（request.js会自动跳转登录页面）
          if (this.isUnauthorizedError(apiError)) {
            console.log('检测到未授权错误，将由request.js自动处理跳转')
            return
          }

          // 解析具体的错误信息
          let errorMessage = '兑换失败，请稍后再试'
          let showRetry = true
          let errorDetails = []

          if (apiError.message) {
            const message = apiError.message

            // 检查是否包含订单验证失败的详细错误
            if (message.includes('订单数据验证失败')) {
              // 尝试从错误中提取具体的验证错误
              if (message.includes('商品已下架')) {
                errorMessage = '商品已下架，无法兑换'
                showRetry = false
              } else if (message.includes('库存不足')) {
                errorMessage = '商品库存不足，请选择其他商品'
                showRetry = false
              } else if (message.includes('积分不足')) {
                errorMessage = '积分不足，无法完成兑换'
                showRetry = false
              } else {
                errorMessage = '商品信息有误，请刷新页面后重试'
                showRetry = true
              }
            } else if (message.includes('积分不足')) {
              errorMessage = '积分不足，无法完成兑换'
              showRetry = false
            } else if (message.includes('库存不足')) {
              errorMessage = '商品库存不足，请选择其他商品'
              showRetry = false
            } else if (message.includes('商品不存在') || message.includes('商品已下架')) {
              errorMessage = '商品不存在或已下架'
              showRetry = false
            } else if (message.includes('timeout')) {
              errorMessage = '网络超时，请重试'
            } else if (message.includes('network')) {
              errorMessage = '网络连接失败，请检查网络后重试'
            } else {
              errorMessage = message
            }
          }

          if (showRetry) {
            uni.showModal({
              title: '兑换失败',
              content: errorMessage,
              confirmText: '重试',
              cancelText: '取消',
              success: (res) => {
                if (res.confirm) {
                  // 延迟重试，避免频繁请求
                  setTimeout(() => {
                    this.processExchange()
                  }, 1000)
                }
              }
            })
          } else {
            // 对于不可重试的错误，显示详细信息并建议用户操作
            let content = errorMessage
            let confirmText = '知道了'
            let showCancel = false

            if (errorMessage.includes('商品已下架')) {
              content = '该商品已下架，您可以浏览其他商品'
              confirmText = '查看其他商品'
              showCancel = true
            } else if (errorMessage.includes('积分不足')) {
              const shortage = this.product.points_price - this.userPointsCount
              content = `当前积分${this.userPointsCount}，还差${shortage}积分。您可以通过完成任务获得更多积分。`
              confirmText = '去赚积分'
              showCancel = true
            }

            uni.showModal({
              title: '兑换失败',
              content: content,
              confirmText: confirmText,
              showCancel: showCancel,
              cancelText: '取消',
              success: (res) => {
                if (res.confirm) {
                  if (errorMessage.includes('商品已下架')) {
                    uni.navigateBack()
                  } else if (errorMessage.includes('积分不足')) {
                    uni.navigateTo({
                      url: '/pages/points/earn'
                    })
                  }
                }
              }
            })
          }
        }
      } catch (error) {
        uni.hideLoading()
        console.error('兑换处理异常:', error)

        uni.showModal({
          title: '兑换异常',
          content: '处理过程中发生异常，请稍后重试',
          confirmText: '重试',
          cancelText: '取消',
          success: (res) => {
            if (res.confirm) {
              setTimeout(() => {
                this.processExchange()
              }, 1000)
            }
          }
        })
      } finally {
        this.loading = false
      }
    },

    // 获取模拟商品数据（仅用于开发阶段）
    getMockProductData() {
      // 根据商品ID返回不同的模拟数据
      const mockProducts = [
        {
          id: 1,
          name: '专业彩色打印服务',
          description: '高质量彩色打印，适用于各类文档、图片、海报等。使用进口墨水，色彩鲜艳持久。支持多种纸张类型，满足不同需求。',
          points_price: 100,
          original_price: 15.00,
          stock: 999,
          image_url: '/static/icons/default-product.svg',
          category: 'print',
          type: 'color',
          is_hot: true,
          is_new: false,
          specifications: {
            paper_type: 'coated',
            paper_weight: '120',
            paper_size: 'A4',
            color_mode: 'color',
            sides: 'double',
            dpi: '1200',
            finish: 'glossy'
          }
        },
        {
          id: 2,
          name: '黑白文档打印',
          description: '经济实惠的黑白打印服务，适合日常文档、作业、报告等。清晰度高，成本低廉。',
          points_price: 50,
          original_price: 8.00,
          stock: 999,
          image_url: '/static/icons/default-product.svg',
          category: 'print',
          type: 'black_white',
          is_hot: false,
          is_new: false,
          specifications: {
            paper_type: 'normal',
            paper_weight: '80',
            paper_size: 'A4',
            color_mode: 'black',
            sides: 'single',
            dpi: '600',
            finish: 'matte'
          }
        },
        {
          id: 3,
          name: '螺旋装订服务',
          description: '专业螺旋装订，可180度平摊，适合笔记本、日历、教材等装订。牢固耐用，美观实用。',
          points_price: 80,
          original_price: 12.00,
          stock: 500,
          image_url: '/static/icons/default-product.svg',
          category: 'binding',
          type: 'spiral_binding',
          is_hot: false,
          is_new: true,
          specifications: {
            binding_type: 'spiral',
            max_pages: 120,
            cover_options: '透明封面+硬卡纸封底',
            colors: '黑色、白色、蓝色可选',
            material: '优质塑料螺旋圈'
          }
        },
        {
          id: 4,
          name: '高档铜版纸彩印',
          description: '使用进口铜版纸，适合高端宣传册、画册、菜单等印刷品。色彩饱和度高，质感优异。',
          points_price: 150,
          original_price: 25.00,
          stock: 300,
          image_url: '/static/icons/default-product.svg',
          category: 'print',
          type: 'color',
          is_hot: true,
          is_new: true,
          specifications: {
            paper_type: 'coated',
            paper_weight: '200',
            paper_size: 'A4',
            color_mode: 'color',
            sides: 'double',
            dpi: '2400',
            finish: 'glossy'
          }
        },
        {
          id: 5,
          name: 'A3大幅面打印',
          description: 'A3大幅面打印，适合海报、图纸、大型表格等。支持彩色和黑白两种模式。',
          points_price: 120,
          original_price: 20.00,
          stock: 200,
          image_url: '/static/icons/default-product.svg',
          category: 'print',
          type: 'color',
          is_hot: false,
          is_new: false,
          specifications: {
            paper_type: 'normal',
            paper_weight: '100',
            paper_size: 'A3',
            color_mode: 'color',
            sides: 'single',
            dpi: '1200',
            finish: 'matte'
          }
        }
      ];

      // 根据ID返回对应的模拟数据，如果没有找到则返回第一个
      return mockProducts.find(p => p.id === this.productId) || mockProducts[0];
    },

    // 处理图片加载错误
    handleImageError() {
      if (this.product) {
        this.product.image_url = this.defaultImageUrl
      }
    },

    // 检查用户认证状态
    checkAuth() {
      return this.isLoggedIn && this.userInfo
    },

    // 跳转到登录页面
    goToLogin(redirectUrl) {
      const loginUrl = redirectUrl ? `/pages/auth/login?redirect=${encodeURIComponent(redirectUrl)}` : '/pages/auth/login'
      uni.navigateTo({
        url: loginUrl
      })
    },

    // 检查是否为未授权错误
    isUnauthorizedError(error) {
      if (!error) return false
      const message = error.message || error.toString()
      return message.includes('未授权') ||
        message.includes('请先登录') ||
        message.includes('登录已过期') ||
        message.includes('token')
    },

    // 返回上一页
    goBack() {
      uni.navigateBack({
        fail: () => {
          uni.switchTab({
            url: '/pages/index/index'
          })
        }
      })
    }
  }

}
</script>

<style lang="scss" scoped>
.container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80vh;
}

.error-state {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 80vh;

  .error-icon {
    width: 120rpx;
    height: 120rpx;
    margin-bottom: 30rpx;
  }

  .error-text {
    font-size: 32rpx;
    color: #999;
    margin-bottom: 40rpx;
  }
}

.product-detail {
  background-color: #fff;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.product-image {
  position: relative;
  width: 100%;
  height: 500rpx;

  .image {
    width: 100%;
    height: 100%;
  }

  .tags {
    position: absolute;
    top: 20rpx;
    left: 20rpx;
    display: flex;

    .tag {
      padding: 6rpx 16rpx;
      border-radius: 6rpx;
      font-size: 24rpx;
      color: #fff;
      margin-right: 10rpx;
    }

    .hot-tag {
      background-color: #ff4d4f;
    }

    .new-tag {
      background-color: #52c41a;
    }
  }
}

.product-info {
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;

  .product-name {
    font-size: 36rpx;
    font-weight: bold;
    margin-bottom: 20rpx;
    color: #333;
  }

  .product-price {
    display: flex;
    align-items: baseline;
    margin-bottom: 20rpx;

    .points-price {
      display: flex;
      align-items: baseline;

      .price-number {
        font-size: 48rpx;
        font-weight: bold;
        color: #ff6b00;
      }

      .price-unit {
        font-size: 28rpx;
        color: #ff6b00;
        margin-left: 8rpx;
      }
    }

    .original-price {
      font-size: 24rpx;
      color: #999;
      text-decoration: line-through;
      margin-left: 20rpx;
    }
  }

  .product-stock {
    margin-bottom: 20rpx;

    .in-stock {
      font-size: 26rpx;
      color: #52c41a;
    }

    .out-of-stock {
      font-size: 26rpx;
      color: #ff4d4f;
    }
  }

  .product-category,
  .product-type {
    display: flex;
    margin-bottom: 10rpx;

    .label {
      font-size: 26rpx;
      color: #666;
      width: 80rpx;
    }

    .value {
      font-size: 26rpx;
      color: #333;
      flex: 1;
    }
  }
}

.product-description {
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;

  .section-title {
    font-size: 30rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
    position: relative;
    padding-left: 20rpx;

    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 6rpx;
      width: 8rpx;
      height: 30rpx;
      background-color: #1890ff;
      border-radius: 4rpx;
    }
  }

  .description-content {
    font-size: 28rpx;
    color: #666;
    line-height: 1.6;
  }
}

.product-specifications {
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;

  .section-title {
    font-size: 30rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
    position: relative;
    padding-left: 20rpx;

    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 6rpx;
      width: 8rpx;
      height: 30rpx;
      background-color: #1890ff;
      border-radius: 4rpx;
    }
  }

  .spec-list {
    .spec-item {
      display: flex;
      margin-bottom: 16rpx;

      .spec-label {
        font-size: 26rpx;
        color: #666;
        width: 160rpx;
        flex-shrink: 0;
      }

      .spec-value {
        font-size: 26rpx;
        color: #333;
        flex: 1;

        .spec-detail {
          display: block;
          font-size: 24rpx;
          color: #999;
          margin-top: 4rpx;
        }
      }
    }
  }
}

.bottom-actions {
  padding: 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .user-points {
    display: flex;
    align-items: baseline;

    .points-label {
      font-size: 26rpx;
      color: #666;
    }

    .points-value {
      font-size: 32rpx;
      font-weight: bold;
      color: #ff6b00;
      margin-left: 10rpx;
    }
  }

  .action-buttons {
    .btn {
      padding: 16rpx 40rpx;
      border-radius: 40rpx;
      font-size: 28rpx;
      font-weight: bold;
      border: none;
    }

    .btn-primary {
      background-color: #ff6b00;
      color: #fff;

      &:disabled {
        background-color: #ccc;
        color: #fff;
      }
    }

    .btn-secondary {
      background-color: #f0f0f0;
      color: #666;
    }
  }
}

.loading-state,
.error-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 60vh;

  .error-icon {
    width: 120rpx;
    height: 120rpx;
    margin-bottom: 40rpx;
  }

  .error-text {
    font-size: 28rpx;
    color: #999;
    margin-bottom: 40rpx;
  }
}

.product-detail {
  background-color: white;
  border-radius: 16rpx;
  overflow: hidden;
  margin-bottom: 120rpx;
}

.product-image {
  position: relative;
  width: 100%;
  height: 400rpx;

  .image {
    width: 100%;
    height: 100%;
  }

  .tags {
    position: absolute;
    top: 20rpx;
    left: 20rpx;
    display: flex;
    gap: 10rpx;

    .tag {
      padding: 8rpx 16rpx;
      border-radius: 20rpx;
      font-size: 20rpx;
      color: white;

      &.hot-tag {
        background-color: #ff4757;
      }

      &.new-tag {
        background-color: #2ed573;
      }
    }
  }
}

.product-info {
  padding: 30rpx;

  .product-name {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
    line-height: 1.4;
  }

  .product-price {
    display: flex;
    align-items: baseline;
    justify-content: space-between;
    margin-bottom: 20rpx;

    .points-price {
      display: flex;
      align-items: baseline;

      .price-number {
        font-size: 48rpx;
        font-weight: bold;
        color: #007aff;
      }

      .price-unit {
        font-size: 24rpx;
        color: #007aff;
        margin-left: 8rpx;
      }
    }

    .original-price {
      font-size: 24rpx;
      color: #999;
      text-decoration: line-through;
    }
  }

  .product-stock {
    margin-bottom: 20rpx;

    .in-stock {
      color: #2ed573;
      font-size: 24rpx;
    }

    .out-of-stock {
      color: #ff4757;
      font-size: 24rpx;
    }
  }

  .product-category,
  .product-type {
    display: flex;
    align-items: center;
    margin-bottom: 10rpx;

    .label {
      font-size: 24rpx;
      color: #666;
      margin-right: 10rpx;
    }

    .value {
      font-size: 24rpx;
      color: #333;
    }
  }
}

.product-description,
.product-specifications {
  padding: 30rpx;
  border-top: 1rpx solid #f0f0f0;

  .section-title {
    font-size: 28rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }

  .description-content {
    font-size: 26rpx;
    color: #666;
    line-height: 1.6;
  }

  .spec-list {
    .spec-item {
      display: flex;
      align-items: flex-start;
      margin-bottom: 16rpx;

      .spec-label {
        font-size: 24rpx;
        color: #666;
        min-width: 140rpx;
        margin-right: 20rpx;
      }

      .spec-value {
        font-size: 24rpx;
        color: #333;
        flex: 1;

        .spec-detail {
          display: block;
          font-size: 22rpx;
          color: #999;
          margin-top: 4rpx;
        }
      }
    }
  }
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: white;
  padding: 20rpx 30rpx;
  border-top: 1rpx solid #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .user-points {
    display: flex;
    align-items: center;

    .points-label {
      font-size: 24rpx;
      color: #666;
      margin-right: 10rpx;
    }

    .points-value {
      font-size: 28rpx;
      font-weight: bold;
      color: #007aff;
    }
  }

  .action-buttons {
    .btn {
      padding: 20rpx 40rpx;
      border-radius: 50rpx;
      font-size: 28rpx;
      border: none;

      &.btn-primary {
        background-color: #007aff;
        color: white;

        &:disabled {
          background-color: #ccc;
          color: #999;
        }
      }

      &.btn-secondary {
        background-color: #f0f0f0;
        color: #666;
      }
    }
  }
}
</style>